import React from 'react';
import { message } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import connectFn from '@/utils/connectFn';
import Mixins from '@/components/Common/mixin';
import CreateCard from '@/components/CreateCard';
import CreateForm from '@/components/CreateForm';
import CreateTable from '@/components/CreateTable';
import CreateModal from '@/components/CreateModal';
import { getFormData, getTableData, getModalData } from './config';
import { StateType } from '@/common-typings';
import Details from './details';
import constant from '@/const';
import OperationResultPage from '@/components/OperationResultPage';
import Observer from '@/utils/observer';
import { types } from '@/utils/utils';

const { SUCCESS_CODE } = constant;

const dataFilters = (data: any) => {
  const list: any[] = [];
  if (types(data) === 'array') {
    data = data.filter((i: string) => i);
    data.forEach((item: string) => {
      list.push({
        label: item,
        value: item,
      });
    });
  }
  return list;
};

@connectFn(
  [{ global: ['validator'] }, 'memberReview'],
  ['getUserManageListOprateion', 'getUserManageListFirst', 'getUserManageListSecond'],
)
class MemberOperateReview extends Mixins {
  private bindDetailRef: any;

  // private bindFormRef: any;

  public state = {
    step: 1, // 控制显示第几个页面
    visible: false, // 批量弹窗显示隐藏
    optType: 1, // 批量操作值
    singleOptType: null, // 单次审核的选中类型， 为了不冲突批量值
    submitLoading: false, // 查询loading
    exportLoading: false, // 导出loading
    reviewLoading: false, // 审核loading
    selectedRowKeys: [], // 多选的managerId Map
    currentRow: {
      manageId: '',
    }, // 点击查看和审核当前行数据存储
    isReview: false, // 当前数据是否已经审核，不用二次判断
    first: [],
    second: [],
    list: [],
    pagination: this.defaultPagination, // 分页信息
    // 数据中心，此处需要前端进行分页展示数据
    dataCenter: {
      loading: false,
      page: 1,
      size: 10,
      total: 0,
      list: [],
    },
    // 操作结果
    operateResult: {
      isSuccess: false,
      message: '',
    },
  };

  componentDidMount(): void {
    this.requestList();
    this.requestFirstMember();
    this.requestSecondMember();
  }

  /**
   * 考虑第三步状态不同的问题
   */
  updateFormData = (data: StateType) => {
    const newParam = _.isEmpty(this.prevFormParams) ? this.defaultFormParams : this.prevFormParams;
    if (!_.isEmpty(newParam) && this.bindFormRef) {
      const deleteList = ['startDate', 'endDate', 'userType', 'dateType'];
      const params = Object.assign({}, newParam);
      const { startDate, endDate } = newParam;

      if (startDate && endDate) {
        params.date = [moment(new Date(startDate)), moment(new Date(endDate))];
      } else {
        params.date = [];
      }

      Object.keys(params).forEach(key => {
        if (deleteList.some(i => i === key)) {
          delete params[key];
        }
      });
      this.bindFormRef.setFieldsValue(params);
    }

    if (data.clear) {
      // 清空选中值
      this.changeState({ selectedRowKeys: [] });
    }
  };

  /**
   * 请求数据
   * @param params
   */
  public requestList = (params: StateType = {}, key?: string) => {
    const { getUserManageListOprateion } = this.props;

    if (params.requireInit) {
      this.updateFormData(params);
      params = {};
    }
    this.changePageLoading({ submitLoading: true });

    getUserManageListOprateion(this.initRequestData(params, key)).then((res: StateType) => {
      const { code, data } = res;
      if (code === SUCCESS_CODE && data) {
        this.updateTableData(data);
      }
      this.changePageLoading({ submitLoading: false });
    });
  };

  /**
   * 更新数据中心
   * @param data
   */
  updateDataCenter = (param = { pageNum: 1, pageSize: 10 }) => {
    // const { pageNum, pageSize } = param;
    const { selectedRowKeys, list } = this.state;
    this.setState(preState => ({
      ...preState,
      dataCenter: {
        ...preState.dataCenter,
        loading: true,
      },
    }));

    // 强行加loading😊😊😊
    setTimeout(() => {
      // @ts-ignore
      const newList = list.filter((item: StateType) => selectedRowKeys.includes(item.manageId));

      // 前端对dataCenter进行分页处理
      // const list = newList.slice((pageNum - 1) * pageSize, pageNum * pageSize);

      this.setState(preState => ({
        ...preState,
        dataCenter: {
          ...preState.dataCenter,
          loading: false,
          total: newList.length,
          // page: param.pageNum,
          // size: param.pageSize,
          list: newList,
        },
      }));
    }, 200);
  };

  /**
   * 获取一审人
   */
  public requestFirstMember = () => {
    this.props.getUserManageListFirst({}).then((res: StateType) => {
      const { code, data } = res;
      if (code === SUCCESS_CODE && data) {
        this.changeState({ first: dataFilters(data) });
      }
    });
  };

  /**
   * 获取二审人
   */
  public requestSecondMember = () => {
    this.props.getUserManageListSecond({}).then((res: StateType) => {
      const { code, data } = res;
      if (code === SUCCESS_CODE && data) {
        this.changeState({ second: dataFilters(data) });
      }
    });
  };

  /**
   * 导出excel
   */
  public exportExcel = (params = {}) => {
    const { dispatch } = this.props;
    if (dispatch) {
      this.changePageLoading({ exportLoading: true });
      dispatch({
        type: 'memberReview/getUserManageDownLoad',
        payload: { ...params },
        fn: (data: any) => {
          this.changePageLoading({ exportLoading: false });
          // 当数据返回成功时，触发下载事件
          if (data.code === 1) {
            Observer.trigger('get-export-download-list', {});
          }
        },
      });
    }
  };

  /**
   * ⚠️ 批量和单次均走该接口，故根据step来判断参数传递
   * @param params
   */
  public handleBatchReview = (params = {}) => {
    const { dispatch } = this.props;
    const { currentRow, step, optType, singleOptType, selectedRowKeys } = this.state;

    if (!selectedRowKeys.length) {
      message.warning('请选择操作数据');
      return;
    }

    if (dispatch) {
      this.changePageLoading({ reviewLoading: true });
      dispatch({
        type: 'memberReview/updateUserManageApproveSecond',
        payload: {
          status: step === 1 ? optType : singleOptType,
          manageId:
            step === 1
              ? this.state.selectedRowKeys.join(',')
              : currentRow.manageId.toString() || '',
          ...params,
        },
        fn: (response: StateType) => {
          if (response.code === 1) {
            this.updateOperationResult(response);
          }
          this.changePageLoading({ reviewLoading: false });
        },
      });
    }
  };

  /**
   * 更新批量操作反馈结果
   * ⚠️单次和批量均走该方法判断逻辑，根据preStep可判断逻辑
   * @param response
   */
  public updateOperationResult = (response: StateType) => {
    const { data } = response;
    const { step, optType, singleOptType } = this.state;
    let text = '';
    if (data && data.hasOwnProperty('successNum')) {
      if (step === 2) {
        text = constant.MEMBER_REVIEW_CHECK_TYPE.filter(i => i.value === singleOptType)[0].label;
        this.setState(preState => ({
          ...preState,
          step: 3,
          visible: false,
          operateResult: {
            isSuccess: !!data.successNum,
            message: data.successNum
              ? `${text}-${data.successNum}条`
              : `${text}-${data.failMessage || '修改失败'}`,
          },
        }));
      } else {
        text = constant.MEMBER_REVIEW_CHECK_TYPE.filter(i => i.value === optType)[0].label;
        this.setState(preState => ({
          ...preState,
          step: 3,
          visible: false,
          operateResult: {
            isSuccess: true,
            message: `${text}-${data.successNum}条`,
          },
        }));
      }
    }
  };

  /**
   * 为逻辑一致性，点击执行按钮皆打开批量审核的弹窗
   * @param params
   */
  public handleOperate = (params: any) => {
    if (this.checkSelectedRowKeys()) {
      this.setState(preState => ({
        ...preState,
        visible: true,
        optType: params.optType,
      }));
      this.updateDataCenter();
    }
  };

  checkSelectedRowKeys = () => {
    let result = false;
    const { selectedRowKeys, list } = this.state;
    if (!selectedRowKeys.length) {
      message.warning('请选择操作数据');
    } else {
      const idList = _.map(list, 'manageId');
      // 判断是否存在
      if (_.difference(selectedRowKeys, idList).length === 0) {
        result = true;
      } else {
        this.changeState({ selectedRowKeys: [] }, () => {
          message.warning('请选择操作数据');
        });
      }
    }

    return result;
  };

  /**
   * 点击取消
   */
  public handleCancel = (params = {}) => {
    this.setState(preState => ({
      ...preState,
      visible: false,
    }));
  };

  /**
   * 点击查看和审核按钮
   * @param row
   * @param isInfo
   */
  public handleReviewInfo = (currentRow: StateType, isReview: boolean) => {
    this.setState(preState => ({
      ...preState,
      isReview,
      currentRow,
    }));
    this.updateStep(2);
  };

  /**
   * 更新当前显示第几页
   * @param step
   * @param callBack
   */
  public updateStep = (step: number, callBack?: Function, clear = false) => {
    this.setState(
      preState => ({
        ...preState,
        step,
      }),
      () => {
        if (callBack) callBack({ requireInit: true, clear });
      },
    );
  };

  /**
   * 点击详情
   * @param value
   */
  handleDetailReview = (value: number) => {
    this.setState(preState => ({
      ...preState,
      visible: true,
      singleOptType: value,
    }));
  };

  /**
   * 调用detail方法，获取dom
   */
  getModalChildren = () => {
    if (this.bindDetailRef) {
      return this.bindDetailRef.renderAccountInfo(false);
    }
    return null;
  };

  public render() {
    const { step, operateResult, currentRow, isReview } = this.state;
    const subTitle = step === 2 ? ['详情'] : [];
    return (
      <CreateCard subTitle={subTitle}>
        {step === 1 && (
          <React.Fragment>
            <CreateForm
              formConfig={getFormData(this)}
              ref={ref => {
                this.bindFormRef = ref;
              }}
            />
            <CreateTable tableConfig={getTableData(this)} />
          </React.Fragment>
        )}
        {step === 2 && (
          <Details
            handleCancel={() => this.updateStep(1, this.requestList)}
            handleDetailReview={this.handleDetailReview}
            isReview={isReview}
            detailData={currentRow}
            memberReview={this.props.memberReview}
            dispatch={this.props.dispatch}
            ref={ref => {
              this.bindDetailRef = ref;
            }}
          />
        )}
        {step === 3 && (
          <OperationResultPage
            {...operateResult}
            goBack={() => this.updateStep(1, this.requestList, true)}
          />
        )}
        <CreateModal modalConfig={getModalData(this)}>{this.getModalChildren()}</CreateModal>
      </CreateCard>
    );
  }
}

export default MemberOperateReview;
